import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User, LoginCredentials } from '@/types/user'
import { authApi } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  const user = ref<User | null>(null)
  const token = ref<string | null>(localStorage.getItem('token'))

  const isAuthenticated = computed(() => !!token.value && !!user.value)

  const login = async (credentials: LoginCredentials) => {
    try {
      const response = await authApi.login(credentials)
      token.value = response.access_token
      user.value = response.user
      localStorage.setItem('token', response.access_token)
      return response
    } catch (error) {
      throw error
    }
  }

  const logout = () => {
    user.value = null
    token.value = null
    localStorage.removeItem('token')
  }

  const updateProfile = async (userData: Partial<User>) => {
    try {
      const response = await authApi.updateProfile(userData)
      user.value = { ...user.value, ...response }
      return response
    } catch (error) {
      throw error
    }
  }

  const getCurrentUser = async () => {
    if (token.value && !user.value) {
      try {
        const response = await authApi.getCurrentUser()
        user.value = response
        return response
      } catch (error) {
        logout()
        throw error
      }
    }
  }

  return {
    user,
    token,
    isAuthenticated,
    login,
    logout,
    updateProfile,
    getCurrentUser
  }
})